import type Database from 'better-sqlite3';
import migrateV2 from './migrations/migrateV2';
import migrateV3 from './migrations/migrateV3';
import migrateV4 from './migrations/migrateV4';

type MigrationFunction = (db: Database.Database) => void;

/**
 * 数据库版本升级迭代
 * migrateV2 migrateV3 演示 v1 -> v2 -> v3
 * @param number: 数据库原始版本号
 * @param MigrationFunction: 迁移函数
 */
const migrations: Record<number, MigrationFunction> = {
  // 1: migrateV2,
  // 2: migrateV3,
  // 3: migrateV4,
};

export default (db: Database.Database) => {
  const version = (
    db.prepare<[string]>('SELECT "field_value" FROM "main"."db_info" WHERE "field_name" = ?').get('version') as {
      field_value: string;
    }
  ).field_value;

  let currentVersion = parseInt(version);
  while (migrations[currentVersion]) {
    migrations[currentVersion](db);
    // 默认升级1个版本
    currentVersion += 1;
    db.prepare('UPDATE "main"."db_info" SET "field_value"=@value WHERE "field_name"=@name').run({
      name: 'version',
      value: currentVersion.toString(),
    });
  }
};
